package com.adb.receivecontent.ui;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.ClipboardManager;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.content.res.Configuration;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.Toast;

import com.adb.receivecontent.R;
import com.adb.receivecontent.bean.LinkMagnetBean;
import com.adb.receivecontent.uc.IPubliceProgress;
import com.adb.receivecontent.uc.ItemRadionListener;
import com.adb.receivecontent.uc.ReceiveContentAdapter;
import com.adb.receivecontent.utility.HttpMultiPartEntitiy;
import com.adb.receivecontent.utility.Pref_Link_Magnet;
import com.adb.receivecontent.utility.UtilityHelper;

public class ReceiveContentActivity extends Activity implements ItemRadionListener,IPubliceProgress{
	
	private final String TAG = ReceiveContentActivity.class.getCanonicalName();
	
	public static final String TASK_COMPLETE_INTENT = "intent.com.adb.receivecontent";
	
	public static String INTENT_MESSAGE;
	
	private Button btn_link_send;
	private ListView listview_check_box_jrg_link;
	private ReceiveContentAdapter mRContentAdapter;
	private Dialog mResultDialog;
	private ClipboardManager clipboard;
	private int indexRadioButton;
	String URLhandlePath;
	ProgressBar mProcessWheel;
	ProgressBar upload_ProgressBar;
	
	private Map<String,String> mLinkKeySets;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		Log.d(TAG," [onCreate] ");
		setContentView(R.layout.activity_receive_contents);
		
		clipboard = (ClipboardManager) getSystemService(CLIPBOARD_SERVICE);
		mProcessWheel = (ProgressBar)findViewById(R.id.toggleIndeterminate_top_bar);
		upload_ProgressBar = (ProgressBar)findViewById(R.id.upload_ProgressBar);
		
		if(savedInstanceState != null){
			
			if(savedInstanceState.get("IsUploadRunning").equals("true")){
				
				URLhandlePath = savedInstanceState.getString("LocalPath");
				
				indexRadioButton  = Integer.parseInt(savedInstanceState.getString("LastIndex"));
				
				int progressState = Integer.parseInt(savedInstanceState.getString("ProgressValue"));
				if(progressState > 0){
					
					upload_ProgressBar.setProgress(progressState);	
				}
				
			}
		}
		
		Intent intent = getIntent();
		String mAction = intent.getAction();
		String mType = intent.getType();
		
		if (Intent.ACTION_SEND.equals(mAction) && mType != null) {
			
			if("text/plain".equals(mType)) {
				
				handleSendText(intent); // Handle text being sent
				
			}else if (mType.startsWith("image/*")) {
				
				handleSendImage(intent); // Handle single image being sent
				
			}else if("application/pdf".equals(mType)) {
			//	Toast.makeText(getApplicationContext(),"MIME/PDF", Toast.LENGTH_LONG).show();
				handlePDFFile(intent);
			}else if (mType.startsWith("audio/*")) {
				handleSendImage(intent); // Handle single image being sent
			}else if (mType.startsWith("video/*")) {
				handleSendImage(intent); // Handle single image being sent
			}else if("text/xml".equals(mType)){
				handleSendImage(intent);
			}else if("text/html".equals(mType)){
				handleSendImage(intent);
			}else if("application/*".equals(mType)){
				handleSendZipFile(intent);
			}else{
				
				Uri unknowFileURI = (Uri) intent.getParcelableExtra(Intent.EXTRA_STREAM);
				if (unknowFileURI != null) {
					URLhandlePath = unknowFileURI.getPath();
				}
			}
			
		} else if (Intent.ACTION_SEND_MULTIPLE.equals(mAction) && mType != null) {
			
			if (mType.startsWith("image/*")) {
				handleSendMultipleImages(intent); // Handle multiple images
			}
		}
		
		
		listview_check_box_jrg_link = (ListView)findViewById(R.id.listview_check_box_jrg_link);
		mRContentAdapter = new ReceiveContentAdapter(ReceiveContentActivity.this);
		listview_check_box_jrg_link.setAdapter(mRContentAdapter);
		if(indexRadioButton > -1){
			
			mRContentAdapter.checkableItemInList(indexRadioButton);
		}
		listview_check_box_jrg_link.setEmptyView(findViewById(R.id.empty));
		
		listview_check_box_jrg_link.setOnItemSelectedListener(new OnItemSelectedListener() {

			@Override
			public void onItemSelected(AdapterView<?> arg0, View arg1,
					int arg2, long arg3) {
				Toast.makeText(getApplicationContext(),"", Toast.LENGTH_SHORT).show();
			
			}

			@Override
			public void onNothingSelected(AdapterView<?> arg0) {
			}
			
		});
		
		btn_link_send = (Button)findViewById(R.id.btn_link_send);
		btn_link_send.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				
				if(UtilityHelper.isOnline(ReceiveContentActivity.this)){
					if(URLhandlePath == null){
						Toast.makeText(getApplicationContext(),"File Path not found !!!",Toast.LENGTH_SHORT).show();
						return;
					}
					if(URLhandlePath.length() > 0 && !URLhandlePath.equals("")){
						
						if(indexRadioButton > -1){
							
//							Toast.makeText(getApplicationContext(),String.valueOf(indexRadioButton),Toast.LENGTH_SHORT).show();
							LinkMagnetBean mTempLinkMagnet = ReceiveContentAdapter.mContentArrayList.get(indexRadioButton);
							new UploadTask().execute(mTempLinkMagnet);	
						}
						
					}else{
						Toast.makeText(getApplicationContext(),"File Path not found !!!",Toast.LENGTH_SHORT).show();
					}
					
						
				}else{
					
					Toast.makeText(getApplicationContext(),"Please check internet connection !!!",Toast.LENGTH_LONG).show();
				}
				
			}
		});
		
		updateAdapter();
	}
	
	@Override
	public void onConfigurationChanged(Configuration newConfig) {
		super.onConfigurationChanged(newConfig);
		// Checks the orientation of the screen
	    if (newConfig.orientation == Configuration.ORIENTATION_LANDSCAPE) {
//	        Toast.makeText(ReceiveContentActivity.this, "landscape", Toast.LENGTH_SHORT).show();
	    } else if (newConfig.orientation == Configuration.ORIENTATION_PORTRAIT){
//	        Toast.makeText(ReceiveContentActivity.this, "portrait", Toast.LENGTH_SHORT).show();
	    }
	}
	
	@Override
	protected void onSaveInstanceState(Bundle outState) {
		super.onSaveInstanceState(outState);
		// url local path 
		outState.putString("LocalPath",URLhandlePath);
		// list view state 
		outState.putString("LastIndex",String.valueOf(indexRadioButton));
		//Progress value
		outState.putString("ProgressValue",String.valueOf(upload_ProgressBar.getProgress()));
		// is upload is running 
		if(btn_link_send.getVisibility() == View.INVISIBLE){
			outState.putString("IsUploadRunning","true");	
		}else if(btn_link_send.getVisibility() == View.VISIBLE){
			outState.putString("IsUploadRunning","false");
		}
		
		
	}
	
	@Override
	protected void onStart() {
		super.onStart();
		Log.d(TAG," [onStart] ");
	}
	
	@Override
	protected void onStop() {
		super.onStop();
		Log.d(TAG," [onStop] ");
	}
	
	@Override
	protected void onPause() {
		super.onPause();
		Log.d(TAG," [onPause] ");
	}
	
	@Override
	protected void onResume() {
		super.onResume();
		Log.d(TAG," [onResume] ");
		
	}
	
	@Override
	protected void onDestroy() {
		super.onDestroy();
		Log.d(TAG," [onDestroy] ");
	}
	
	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		
		if(keyCode == KeyEvent.KEYCODE_BACK){
			ShowExitDialog();
		}
		return super.onKeyDown(keyCode, event);
	}
	
	@Override
	public void onRadioItemLinkClick(boolean flag, int position) {
//		Toast.makeText(getApplicationContext(), "Result :" + flag, Toast.LENGTH_SHORT).show();
		mRContentAdapter.checkableItemInList(position);
		indexRadioButton = position;
	}
	
	public void showAdditionalDialog(final String message) {

		mResultDialog = new Dialog(ReceiveContentActivity.this,R.style.MyDialogTheme);
		mResultDialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
		mResultDialog.setContentView(R.layout.custom_dialog_content_result);

		final EditText mEdit_text_key = (EditText) mResultDialog.findViewById(R.id.edit_text_receive_message);
		if(message != null)
		mEdit_text_key.setText(message);
		
		Button mbtn_addtional_ok = (Button) mResultDialog.findViewById(R.id.btn_content_receive_copy_text);
		Button mbtn_addtional_cancel = (Button) mResultDialog.findViewById(R.id.btn_content_receive_exit);
		Button btn_complete_action = (Button)mResultDialog.findViewById(R.id.btn_content_receive_open);
		mbtn_addtional_cancel.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				mResultDialog.dismiss();
				finish();
			}
		});

		mbtn_addtional_ok.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				
				clipboard.setText(mEdit_text_key.getText());
				Toast.makeText(getApplicationContext(), ""+ clipboard.getText(), Toast.LENGTH_SHORT).show();
				mResultDialog.dismiss();
			
			}
		});
		btn_complete_action.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				if(message.contains("http://") || message.contains("https://")){
					Uri webpage = Uri.parse(message);
					Intent webIntent = new Intent(Intent.ACTION_VIEW, webpage);
					PackageManager packageManager = getPackageManager();
					List<ResolveInfo> activities = packageManager.queryIntentActivities(webIntent, 0);
					boolean isIntentSafe = activities.size() > 0;
					  
					// Start an activity if it's safe
					if (isIntentSafe) {
					    startActivity(webIntent);
					}
				}
			}
		});

		mResultDialog.show();
	}
	
	
	void handleSendText(Intent intent) {
		String sharedText = intent.getStringExtra(Intent.EXTRA_TEXT);
		if (sharedText != null) {
		}
	}
	
	void handleSendZipFile(Intent intent){
		Uri zipURI = (Uri) intent.getParcelableExtra(Intent.EXTRA_STREAM);
		if (zipURI != null) {
			if(zipURI.getPath().endsWith(".zip")){
				URLhandlePath = zipURI.getPath();	
			}
		}
	}

	/**
	 * Handle Image Path in Intent
	 * @param intent
	 */
	void handleSendImage(Intent intent) {
		Uri imageUri = (Uri) intent.getParcelableExtra(Intent.EXTRA_STREAM);
		if (imageUri != null) {
			String realPathofconetent = UtilityHelper.getRealPathFromURI(ReceiveContentActivity.this, imageUri);
			if(!realPathofconetent.equalsIgnoreCase("") && realPathofconetent != null){
				URLhandlePath = realPathofconetent;
			}
		}
	}
	
	/**
	 * Handle Pdf document path
	 * @param intent
	 */
	void handlePDFFile(Intent intent) {
		Uri imageUri = (Uri) intent.getParcelableExtra(Intent.EXTRA_STREAM);
		if (imageUri != null) {
			if(imageUri.getPath().endsWith(".pdf")){
				
				URLhandlePath = imageUri.getPath();	
			}
			
		}
	}
	
	
	/**
	 * Handle multiple images path in intent
	 * @param intent
	 */

	void handleSendMultipleImages(Intent intent) {
		ArrayList<Uri> imageUris = intent
				.getParcelableArrayListExtra(Intent.EXTRA_STREAM);
		if (imageUris != null) {
			// Update UI to reflect multiple images being shared
		}
	}
	
	class UploadTask extends AsyncTask<LinkMagnetBean,Void,String>{

		@Override
		protected void onPreExecute() {
			super.onPreExecute();
			mProcessWheel.setVisibility(View.VISIBLE);
			btn_link_send.setVisibility(View.INVISIBLE);
		}
		
		@Override
		protected String doInBackground(LinkMagnetBean... params) {
//			return new HttpUploadFile().postImageIMEI(ReceiveContentActivity.this,URLhandleSendImage,params[0]);
//			return new NewHttpFileUpload().postImageIMEI(ReceiveContentActivity.this,URLhandleSendImage,params[0]);
			HttpMultiPartEntitiy mUploadTask = new HttpMultiPartEntitiy();
			return mUploadTask.postImageIMEI(ReceiveContentActivity.this,URLhandlePath,params[0]);
		}
		
		@Override
		protected void onPostExecute(String result) {
			super.onPostExecute(result);
			mProcessWheel.setVisibility(View.INVISIBLE);
			btn_link_send.setVisibility(View.VISIBLE);
			showAdditionalDialog(result);
		}
		
		
	}

	@Override
	public void setPubliseProgress(final int progress) {
		runOnUiThread(new Runnable() {
			
			@Override
			public void run() {
				Log.d(TAG," Set Progress " + progress);
				upload_ProgressBar.setProgress(progress);	
			}
		});
	}
	
	public void ShowExitDialog(){
		
		AlertDialog.Builder builder = new AlertDialog.Builder(ReceiveContentActivity.this);
		builder.setMessage("Are you sure to exit ?");
		builder.setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
		           public void onClick(DialogInterface dialog, int id) {
		        	   dialog.dismiss();
		        	   finish();
		           }
		       });
		builder.setNegativeButton(android.R.string.cancel, new DialogInterface.OnClickListener() {
		           public void onClick(DialogInterface dialog, int id) {
		        	   dialog.cancel();
		           }
		       });
		AlertDialog mExitDialog = builder.create();
		mExitDialog.show();
	}
	
	public void updateAdapter(){
		
		new AsyncTask<Void,Void,Integer>(){
			
			ArrayList<LinkMagnetBean> mWholeLinklist = null;
			
			@Override
			protected void onPreExecute() {
				super.onPreExecute();
			}
			
			@Override
			protected Integer doInBackground(Void... params) {
				int result = 0;
				
				if(mRContentAdapter !=null){
					
					mWholeLinklist = new ArrayList<LinkMagnetBean>();
					LinkMagnetBean mNewRecord;
					mLinkKeySets = Pref_Link_Magnet.getAllKeySets();
					if(mLinkKeySets != null && mLinkKeySets.size() > 0){
						
						Iterator<Map.Entry<String,String>> linkEntries = mLinkKeySets.entrySet().iterator();
						while(linkEntries.hasNext()){
							
							Map.Entry<String,String> mLinkEntry = linkEntries.next();
							String keyID = mLinkEntry.getKey(); 
							String completeEntry = mLinkEntry.getValue();
							
							Log.d(TAG,"KEYID :" + keyID);
							Log.d(TAG,"VALUE :" + completeEntry);
							
							mNewRecord = new LinkMagnetBean();
							mNewRecord.setStrLinkID(keyID); // Key ID
							mNewRecord.extractWholeString(completeEntry);
							mWholeLinklist.add(mNewRecord);
						}
						
					}else{
						
						result = -1;
					}
					
				}else{
					
					result = -1;
				}
				
				return result;
			}
			
			@Override
			protected void onPostExecute(Integer result) {
				super.onPostExecute(result);
				if(result == 0){
					
					mRContentAdapter.addLinksItems(mWholeLinklist);
				}
			}
			
		}.execute();
		
	}
	
}
